<template>
  <section class="flex flex-col h-full">
    <el-form :model="queryParams" @submit.native.prevent ref="queryFormRef" :inline="true" label-width="80px">
      <el-form-item label="" prop="">
        <el-radio-group v-model="queryParams.dateType" @change="changeDateType">
          <el-radio-button label="daterange" value="daterange">日报表</el-radio-button>
          <el-radio-button label="month" value="month">月报表</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="统计时间" prop="timerulemonth" v-show="queryParams.dateType == 'month'">
        <el-select
          v-model="defaultday"
          placeholder="请选择日期"
          style="width: 120px;height: 36px !important;"
        >
          <el-option
            v-for="dict in daytypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-time-picker
          v-model="timerulemonth"
          placeholder="请选择时间"
          default-value="00:00:00"
          value-format="HH:mm:ss"
          :clearable="false"
          :editable="false"
          @change="changeTime"
          class="form-time-height"
        />
      </el-form-item>
      <el-form-item label="统计时间" prop="timerule" v-show="queryParams.dateType == 'daterange'">
        <el-time-picker
          v-model="timerule"
          placeholder="请选择时间"
          default-value="00:00:00"
          value-format="HH:mm:ss"
          :clearable="false"
          :editable="false"
          @change="changeTime"
          class="form-time-height"
        />
      </el-form-item>
      <el-form-item prop="orderPeriod" v-show="queryParams.dateType == 'daterange'">
        <el-select v-model="searchNameVal" placeholder="请选择时间类型" style="width: 120px">
          <el-option
            v-for="dict in timetypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-date-picker
          v-model="period"
          value-format="YYYY-MM-DD"
          :clearable="false"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="form-item-height"
        />
      </el-form-item>
      <el-form-item prop="orderPeriod" v-show="queryParams.dateType == 'month'">
        <el-select v-model="searchNameVal" placeholder="请选择时间类型" style="width: 120px">
          <el-option
            v-for="dict in timetypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-date-picker
          v-model="timeRange"
          type="monthrange"
          range-separator="-"
          @change="choseDateByMonth"
          :clearable="false"
          :teleported="true"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          value-format="YYYY-MM"
          class="form-item-height"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="所属企业" prop="outTenantId"
                    :rules="[{ required: true, message: '所属企业不能为空', trigger: 'change' }]">
        <el-select filterable v-model="queryParams.outTenantId" placeholder="请选择所属企业" class="!w-200px"
                   @change="handleTenantChange">
          <el-option v-for="item in tenantList" :key="item.id" :label="item.enterName" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="客户企业" prop="customerId">
        <el-select clearable filterable v-model="queryParams.customerId" placeholder="请选择客户企业" class="!w-200px">
          <el-option v-for="item in customerList" :key="item.customerId" :label="item.customerName"
                     :value="item.customerId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          class="!w-200px"
          clearable
          maxlength="50"
          placeholder="请输入产品名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          统计
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <div class="flex justify-between mb-16px">
      <div>
        <el-button
          type="primary"
          @click="handleExport(1)"
          :loading="exportCusLoading"
          v-hasPermi="['salesReport:exportCus']"
        >
          按客户导出
        </el-button>
        <el-button
          type="primary"
          @click="handleExport(2)"
          :loading="exportCusProLoading"
          v-hasPermi="['salesReport:exportCusPro']"
        >
          按客户产品导出
        </el-button>
      </div>
      <div>
        <el-button @click="toggle">
          <el-tooltip effect="dark" content="全屏" placement="top-start">
            <div style="width: 22px;height: 22px;">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                <path d="M8 3V5H4V9H2V3H8ZM2 21V15H4V19H8V21H2ZM22 21H16V19H20V15H22V21ZM22 9H20V5H16V3H22V9Z"></path>
              </svg>
            </div>
          </el-tooltip>
        </el-button>
      </div>
    </div>
    <el-table class="flex-1" ref="singleTableRef" v-loading="loading" :data="list" border stripe
              @selection-change="selectionChange" show-summary row-key="id" :summary-method="getSummaries"
              :header-cell-style="{ background: '#F3F4F7', color: '#555' }" height="100%">
      <el-table-column label="" width="60" align="center" fixed="left">
        <template slot-scope="">
          <svg-icon icon-class="up" class="show-icon"/>
          <svg-icon icon-class="down" class="hidden-icon"/>
        </template>
      </el-table-column>
      <el-table-column
        :label="queryParams.dateType == 'daterange' ? '统计日期' : '统计月'"
        align="center"
        prop="statisticsTime"
        fixed="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="客户名称"
        align="center"
        prop="customerName"
        fixed="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="产品"
        align="center"
        prop="productName"
        fixed="left"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="车数" align="center" prop="carNumber"/>
      <el-table-column label="毛重(吨)" align="center" prop="grossWeight"/>
      <el-table-column label="皮重(吨)" align="center" prop="netWeight"/>
      <el-table-column label="净重(吨)" align="center" prop="totalWeight"/>
      <el-table-column label="单价(元)" align="center" prop="productPrice"/>
      <el-table-column label="合计金额(元)" align="center" prop="priceTotal"/>
    </el-table>
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
                @pagination="getList"/>
  </section>
</template>

<script setup lang="ts" name="SalesReport">
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import * as reportManageApi from '@/api/reportManage'
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import {useFullscreen} from "@vueuse/core";
import * as authorizationManageApi from "@/api/authorizationManage";

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化
const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const listTotal = ref([]) // 列表的数据
const exportCusLoading = ref(false) // 导出的加载中
const exportCusProLoading = ref(false) // 导出的加载中
const singleTableRef = ref()
const {isFullscreen, toggle} = useFullscreen(singleTableRef)
const searchNameVal = ref('20')
const timetypeList = [
  {
    value: '10',
    label: '轻磅时间'
  },
  {
    value: '20',
    label: '重磅时间'
  }
  // {
  //   value: '30',
  //   label: '完成时间'
  // },
]
const period = ref([])
const timeRange = ref([])
const defaultday = ref('')
const timerule = ref('00:00:00')
const timerulemonth = ref('00:00:00')
const queryFormRef = ref() // 搜索的表单

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  dateType: 'daterange',
  outTenantId: undefined,
  customerId: undefined,
  productName: undefined,
  statisticsTimeType: undefined,
  startTime: undefined,
  endTime: undefined,
  statisticsRule: undefined,
  authId: undefined,
  customerIdList: []
})

/** 获取所属企业 */
const tenantList = ref([])
const getOutTenantList = async () => {
  const res = await authorizationManageApi.getOutTenantListByIdentity({identity: 1})
  tenantList.value = res || []
  if (tenantList.value.length > 0) {
    queryParams.outTenantId = tenantList.value[0].id
    // 获取对应的客户企业列表
    await getCustomerList(tenantList.value[0].id)
  }
}

/** 根据所属企业获取客户企业 */
const customerList = ref([])
const getCustomerList = async (tenantId) => {
  if (!tenantId) return
  const res = await reportManageApi.getOutCustomerListByIdentity({outTenantId: tenantId, identity: 1})
  customerList.value = res || []
}

/** 切换所属企业重新获取客户企业 */
const handleTenantChange = async (tenantId) => {
  await getCustomerList(tenantId)
  // 清空之前选择的客户企业
  queryParams.customerId = undefined
}

const selectionChange = (selection) => {
  if (selection.length > 1) {
    singleTableRef.value.clearSelection()
    singleTableRef.value.toggleRowSelection(selection[selection.length - 1])
  }
}

/** tab切换 */
const changeDateType = async (e) => {
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  if (e == 'daterange') {
    queryParams.dateType = 'daterange'
    resetQuery()
  } else {
    queryParams.dateType = 'month'
    resetQuery()
  }
}

/** 查询列表 */
const getList = async () => {
  if (!queryParams.outTenantId) {
    return
  }
  queryParams.authId = queryParams.outTenantId
  queryParams.customerIdList = queryParams.customerId ? [queryParams.customerId] : []
  loading.value = true
  try {
    if (queryParams.dateType == 'month') {
      queryParams.statisticsRule = defaultday.value + ' ' + timerulemonth.value
      queryParams.startTime = timeRange.value[0]
      queryParams.endTime = timeRange.value[1]
    } else {
      queryParams.statisticsRule = timerule.value
      queryParams.startTime = period.value[0]
      queryParams.endTime = period.value[1]
    }
    queryParams.statisticsTimeType = searchNameVal.value
    let data = await reportManageApi.getSalesDayOrMonthListPage(queryParams)
    if (!!data) {
      listTotal.value = data.extInfo || {}
      list.value = handleMonthList(data.list || [])
      total.value = data.total || 0
    } else {
      listTotal.value = {}
      list.value = []
      total.value = 0
    }
  } finally {
    loading.value = false
  }
}

const handleMonthList = (list) => {
  return list.map((e, v) => {
    e.index = v + 1
    e.id = e.id + 1
    if (e.children?.length) {
      e.children = e.children.map((m, n) => {
        m.id = e.id + ',' + n++
        m.statisticsTime = undefined
        m.customerId = undefined
        return m
      })
    }
    return e
  })
}

/** 合计 */
const getSummaries = (param) => {
  const {columns, data} = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (
      ['carNumber', 'grossWeight', 'netWeight', 'totalWeight', 'priceTotal'].includes(
        column.property
      )
    ) {
      sums[index] = listTotal.value[column.property]
      return
    }
  })
  return sums
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.pageNo = 1
  const valid = await queryFormRef.value.validate()
  if (!valid) return
  getList()
}

/** 月份选择 */
const choseDateByMonth = async () => {
  const formatDate = (date) => {
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    return `${year}-${month}`
  }
  timeRange.value = [formatDate(timeRange.value[0]), formatDate(timeRange.value[1])]
}
const changeTime = async () => {
  console.log(timerule.value)
}

/** 重置按钮操作 */
const resetQuery = async () => {
  searchNameVal.value = '20'
  timerule.value = '00:00:00'
  timerulemonth.value = '00:00:00'
  await getDefaultDayRange()
  await getDefaultMonthRange()
  queryFormRef.value.resetFields()
  if (tenantList.value.length > 0) {
    queryParams.outTenantId = tenantList.value[0].id
    await getCustomerList(tenantList.value[0].id)
  }
  handleQuery()
}

/** 导出按钮操作 */
const handleExport = async (type) => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    if (type === 1) {
      // 发起导出
      exportCusLoading.value = true
      const data = await reportManageApi.exportByCustomer(queryParams)
      if (queryParams.dateType == 'month') {
        download.excel(data, '客户月报表.xls')
      } else {
        download.excel(data, '客户日报表.xls')
      }
    } else {
      exportCusProLoading.value = true
      const data = await reportManageApi.exportByCustomerAndProduct(queryParams)
      if (queryParams.dateType == 'month') {
        download.excel(data, '客户产品月报表.xls')
      } else {
        download.excel(data, '客户产品日报表.xls')
      }
    }
  } catch {
  } finally {
    exportCusLoading.value = false
    exportCusProLoading.value = false
  }
}
/** 默认月份 **/
const getDefaultMonthRange = () => {
  const now = new Date() // 当前日期
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth() + 1 // 当前月份（1-12）

  // 计算上个月的年份和月份
  let lastMonthYear = currentYear
  let lastMonth = currentMonth - 1
  if (lastMonth < 1) {
    lastMonth = 12
    lastMonthYear = currentYear - 1
  }

  // 格式化日期为 YYYY-MM-dd
  const formatDate1 = (year, month) => {
    return `${year}-${String(month).padStart(2, '0')}`
  }

  timeRange.value = [
    formatDate1(lastMonthYear, lastMonth), // 上个月
    formatDate1(currentYear, currentMonth) // 当前月
  ]
  defaultday.value = '01'
}
/** 默认日期 **/
const getDefaultDayRange = () => {
  // 获取默认日期范围（昨天到今天）
  const now = new Date() // 当前日期
  const today = new Date(now) // 今天的日期
  const yesterday = new Date(now) // 昨天的日期
  yesterday.setDate(now.getDate() - 1) // 设置为昨天

  // 格式化日期为 YYYY-MM-dd
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0') // 月份补零
    const daterange = String(date.getDate()).padStart(2, '0') // 日期补零
    return `${year}-${month}-${daterange}`
  }
  period.value = [formatDate(yesterday), formatDate(today)]
}
/** 日期默认28天 */
const daytypeList = Array.from({length: 28}, (_, i) => ({
  value: String(i + 1).padStart(2, '0'),
  label: String(i + 1).padStart(2, '0')
}))

/** 初始化 **/
onMounted(async () => {
  await getDefaultDayRange()
  await getDefaultMonthRange()
  await getOutTenantList()
  getList()
})
</script>

<style lang="scss" scoped>
:deep(.el-table__header-wrapper .el-checkbox__inner) {
  display: none !important;
}

.el-table {
:deep(.el-button) {
  height: 30px !important;
  line-height: 30px !important;
}
}
</style>
